package com.agg.persist.provider;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.builder.annotation.ProviderContext;

import java.text.MessageFormat;
import java.util.List;
import java.util.StringJoiner;

public class InsertTemplateProvider {

    private final static String space=" ";

    public String insertTemplate(@Param("table")String table,  List<String> columns,List<String>  propertys,@Param("list")List list){

        StringJoiner joiner = new StringJoiner(space);
        joiner.add("INSERT INTO");
        joiner.add(table);
        joiner.add("(");
        //拼接插入列
        StringJoiner columnJoins=new StringJoiner(",");
        for(String column:columns){
            columnJoins.add(column);
        }
        joiner.add(columnJoins.toString());
        joiner.add(")");
        joiner.add("VALUES");
        StringJoiner propertyJoiner=new StringJoiner(",");
        for(String key:propertys){
            propertyJoiner.add("#'{'list[{0}]."+key+"}");
        }
        StringBuilder builder=new StringBuilder();
        builder.append("(").append(propertyJoiner.toString()).append(")");
        System.out.println("mf==============="+builder.toString());
        MessageFormat mf = new MessageFormat(builder.toString());
        StringBuilder sb = new StringBuilder();
        int length=list.size();
        for(int i=0;i<length;i++){
            String valueGroup=mf.format(new Object[]{i});
            sb.append(valueGroup);
            if (i < length - 1) {
                sb.append(",");
            }
        }
        joiner.add(sb.toString());
        String sql=joiner.toString();
        System.out.println("sql template=========="+sql);
        return sql;
    }

    public String insertTemplate1(@Param("table")String table,
                                 List<String> columns,
                                 List<String>  propertys,
                                 @Param("list")List list,
                                 ProviderContext context){
        StringJoiner joiner = new StringJoiner(space);
        String templateSql=null;
        joiner.add("insert");
        joiner.add(table);
        joiner.add("(");
        for(String column:columns){
            joiner.add(column+",");
        }
        joiner.add(")");
        joiner.add("values");
        joiner.add("<foreach collection ='list' item='item' separator =','>");
        StringJoiner propertyJoiner=new StringJoiner(",");
        for(String key:propertys){
            propertyJoiner.add("#{item."+key+"}");
        }
        StringBuilder builder=new StringBuilder();
        builder.append("(").append(propertyJoiner.toString()).append(")");
        joiner.add(builder.toString());
        joiner.add("</foreach>");
        return templateSql;
    }
}
